import { loadSprite } from "./helper/Loader";
import storage from './helper/DATA/localstorage'
import { setHomeBtn } from './helper/UI/StaticNode'
import SoundManager from './Manager/SoundManager'
const { ccclass, property } = cc._decorator;

@ccclass
export default class LetterGame extends cc.Component {
    level: number = 1 // 关卡登记
    questionBank = [] // 题库
    answerGroup = []  // 当前题目所有答案
    answerOption = [] // 备选字母
    userAnswer = [] // 当前用户答题
    optionGroupNode: cc.Node = null // 答题条件节点
    group = null
    lineDict = []
    drawContext: cc.Graphics = null
    num = 0
    // 答题条件的位置
    optPositionDict = []
    // 激活条件
    touchData = []
    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        setHomeBtn(this)
        this.initGame()
        // 开启碰撞检测
        const manager = cc.director.getCollisionManager()
        manager.enabled = true;
        if (CC_DEBUG) {
            manager.enabledDebugDraw = true;
            cc.log(manager)
        }
        SoundManager.getInstance().playMusic('en')
    }
    update(dt) {
        while (this.lineDict.length) {
            const { x, y } = this.lineDict.shift()
            // const position = this.group.convertToNodeSpaceAR(cc.v2(x,y))
            // cc.log(x,y,position)
            // this.drawContext.lineTo(position.x, position.y)
            this.drawContext.lineTo(x, y)
            this.drawContext.stroke()
            this.drawContext.moveTo(x, y)
            this.num += 1
            cc.log(this.num)
            // 判断是否划到了字母区域内
            this.optPositionDict.forEach((el, index) => {
                const { x0, y0, x1, y1 } = el
                if (x > x0 && x < x1 && y > y0 && y < y1) {
                    // 没有被锁定的条件，添加到答案中
                    if (!el.lock) {
                        this.touchData.push(el.sign)
                        el.lock = true
                    }
                } else {
                    el.lock = false
                }
            })
        }
        // cc.log(this.lineDict)
    }
    start() {
        cc.log('start', this)
        this.group = new cc.Node('draw')
        this.group.width = this.node.width
        this.group.height = this.node.height / 2
        this.node.addChild(this.group)
        this.drawContext = this.group.addComponent(cc.Graphics)
        this.drawContext.strokeColor = cc.color(133, 101, 105)
        this.drawContext.lineWidth = 5
        this.drawContext.lineJoin = cc.Graphics.LineJoin.ROUND
        this.drawContext.lineCap = cc.Graphics.LineCap.ROUND

        if (CC_DEBUG) {
            const coll = this.group.addComponent(cc.BoxCollider)
            coll.size = cc.size(this.group.width, this.group.height)
        }
        // 设置线条宽度
        this.node.on(cc.Node.EventType.TOUCH_START, this.touch_start, this)
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touch_move, this)
        this.node.on(cc.Node.EventType.TOUCH_END, this.touch_end, this)
    }
    /**
     * @description  初始化游戏信息，包括关卡、题库、当前题目
     * @author 刘建文
     * @date 2019-12-23
     * @memberof LetterGame
     */
    async initGame() {
        // TODO: 关卡信息，总计题目数
        this.level = Number(storage.get('letter_level')) || 1
        const { json: questionBank } = await loadSprite('data/questionBank', cc.JsonAsset)
        this.questionBank = questionBank
        this.optionGroupNode = new cc.Node('optionGroupNode')
        this.node.addChild(this.optionGroupNode)
        const answerLayout = this.node.getChildByName('answer_list')
        answerLayout.width = this.node.width * 0.8
        // 加载题目
        this.loadQuestion(this.level)
        const levelNode = new cc.Node()
        this.node.addChild(levelNode)
        levelNode.position = cc.v2((this.node.width / 2) - 50, (this.node.height / 2) - 70)
        cc.log(this.node.width)
        const levelString = levelNode.addComponent(cc.Label)
        levelString.fontSize = 20
        levelString.string = `关卡:${storage.get('letter_level')}`
    }
    addAnswer(answer) {
        cc.log(answer)
        const answerLayout = this.node.getChildByName('answer_list')
        // answerLayout.width = 200 // 不知道为啥变宽了
        const answerNode = new cc.Node(`user_answer_${answer}`)
        const label = answerNode.addComponent(cc.Label)
        label.string = `${answer}`
        label.fontSize = 16
        label.lineHeight = 30
        answerNode.color = cc.color(133, 101, 105)
        answerLayout.addChild(answerNode)
    }
    /**
     * @description     加载当前题目  
     * @author 刘建文
     * @date 2019-12-23
     * @param {string} [level='1']  当前关卡等级
     * @memberof LetterGame
     */
    async loadQuestion(level = 1) {
        this.answerGroup = this.questionBank.filter(e => {
            return e.level === level.toString()
        }).reduce((a, b) => a.concat([b.data.trim()]), [])

        this.answerOption = Array.from(new Set(this.answerGroup.reduce((a, b) => a.concat(...b.split('')), [])))

        if (this.answerGroup.length !== 0) {
            storage.set('letter_level', level)
        }
        this.optionGroupNode.removeAllChildren()
        const len = 360 / this.answerOption.length
        const radius = 100
        const offsetY = -100
        for (const i in this.answerOption) {
            const node = new cc.Node(`letter_option_${i}`)
            this.optionGroupNode.addChild(node)

            // this.node.addChild(node)
            const sp = node.addComponent(cc.Sprite)
            const texture = await loadSprite('image/letter_option', cc.Texture2D)
            const { x, y } = this.getOptionSprite(this.answerOption[i])
            sp.spriteFrame = new cc.SpriteFrame(texture, new cc.Rect(x * 70, y * 110, 70, 110), false, cc.Vec2.ZERO, cc.size(70, 110))

            node.width = 35
            node.height = 55
            node.zIndex = 100
            let deg = Number(i) * len * Math.PI / 180
            let xp = Math.sin(deg) * radius
            let yp = Math.cos(deg) * radius + offsetY
            node.position = cc.v2(xp, yp)
            cc.log(xp, yp)

            this.optPositionDict.push({
                x0: xp - (node.width / 2),
                x1: xp + (node.width / 2),
                y0: yp - (node.height / 2),
                y1: yp + (node.height / 2),
                lock: false,
                sign: this.answerOption[i]
            })
            if (CC_DEBUG) {
                const collider = node.addComponent(cc.BoxCollider)
                collider.name = `opt_coll_${i}`
                collider.size = cc.size(node.width, node.height)
            }

            cc.log(node.getComponents(cc.BoxCollider))
        }
        const tipNode = new cc.Node()
        this.node.addChild(tipNode)
        const txt = tipNode.addComponent(cc.Label)
        txt.string = `答对${this.answerGroup.length}道题即可通关`
        txt.fontSize = 14
        tipNode.color = cc.color(255, 0, 0)
        tipNode.position = cc.v2(0, (this.node.height / 2) - 75)
    }
    // 获取字母位置
    getOptionSprite(key) {
        const letterArray = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        const num: any = letterArray.indexOf(key)
        const position = {
            x: num % 7, y: Math.floor(num / 7)
        }
        return position
    }
    touch_start(touch) {
        const ctx = this.drawContext
        // 路径起点
        const location = touch.getLocation()
        cc.log(this.node)
        const { x, y } = this.node.convertToNodeSpaceAR(location)
        ctx.moveTo(x, y);
        this.lineDict.push({ x, y })
        cc.log(x, y)
        this.touchData = []

    }
    touch_move(touch) {
        const ctx = this.drawContext
        const location = touch.getLocation()
        const { x, y } = this.node.convertToNodeSpaceAR(location)
        // 添加到update中，统一进行绘图
        this.lineDict.push({ x, y })


    }
    async touch_end(touch) {
        cc.log('over')
        const answerString = this.touchData.join('')
        const index = this.answerGroup.indexOf(answerString)
        cc.log(answerString, this.answerGroup, index)
        if (index >= 0) {
            this.addAnswer(answerString)
            this.userAnswer.push(answerString)
            this.answerGroup.splice(index, 1)
            if (this.answerGroup.length === 0) {
                cc.log('过关')
                this.level += 1
                storage.set('letter_level', this.level)

                const dialogNode = new cc.Node()
                dialogNode.width = this.node.width * 0.6
                dialogNode.height = 200
                this.node.addChild(dialogNode)
                const backNode = new cc.Node()
                dialogNode.addChild(backNode)
                const Texture2D = await loadSprite('image/Common', cc.Texture2D)
                let sp = backNode.addComponent(cc.Sprite)
                const spriteFrame = new cc.SpriteFrame(Texture2D, new cc.Rect(270, 125, 114, 85), false, cc.Vec2.ZERO, cc.size(100, 100))
                sp.spriteFrame = spriteFrame
                backNode.scaleX = dialogNode.width / backNode.width
                backNode.scaleY = dialogNode.height / backNode.height
                const labelNode = new cc.Node()
                labelNode.color = cc.color(109, 100, 196)
                dialogNode.addChild(labelNode)
                const label = labelNode.addComponent(cc.Label)
                label.string = '你真棒!\n准备挑战更高难度吧!'
                label.fontSize = 16
                this.scheduleOnce(() => {
                    cc.director.loadScene('letter')
                }, 3)
            }
        }
        this.clear()
    }
    clear() {
        this.drawContext.clear()
    }

}
